var tablelist = []
//请求用
var storage_rules_config_request = {};
//新增框提交内容容器
var field
//文件类型容器
var filetype_select_option = []
//editable空间容器
// var storage_rule_select_space_arr = []
//editable类型容器
var filetype_select_option_arr = [{"":""}]




$.ajax({
	url: 'http://' + ipm + ':8081/dict/query',
	type: 'POST',
	contentType: 'application/json',
	dataType: 'json',
	data: {},
	success: function (response) {
		storageRulesConfigRead(response)
		var dm8data = response.data;
		var dm8content = dm8data.content;
		var datalist = [];
		var testa;
		var testb;
		for (var i = 0; i < dm8content.length; i++) {
			if (dm8content[i].cfgType == 6) {
				datalist[i] = dm8content[i].content;
				testa = JSON.parse(datalist[i]);
				testb = testa.type_defines;
				for (var j = 0; j < testb.length; j++) {
					filetype_select_option.push(testb[j])
				}
			}
		}
		for (var i = 0; i < filetype_select_option.length; i++) {
			var filetype_select_option_obj = {}
			// filetype_select_option_obj.value = JSON.stringify(filetype_select_option[i]);
			filetype_select_option_obj.value = filetype_select_option[i];
			filetype_select_option_obj.text = filetype_select_option[i];
			filetype_select_option_arr.push(filetype_select_option_obj);
		}



		layui.use(['form'], function () {
			var form = layui.form;
			//使用循环遍历，给下拉列表赋值
			$.each(filetype_select_option, function (index, value) {
				$('#dump_path_select2').append(new Option(value, value));// 下拉菜单里添加元素
				$('#auto_backups_select2').append(new Option(value, value));// 下拉菜单里添加元素
			});

			form.render("select");
		});
		bootstrapTable_init();
	}
});





//新增文件存储规则模态框构建
function createStorageRuleModel() {
	$('#storageRuleModal').modal('show');
}

//模态框步骤构建
layui.config({
	base: 'step-lay/'
}).use(['form', 'step'], function () {
	var $ = layui.$
		, form = layui.form
		, step = layui.step;

	step.render({
		elem: '#stepForm',
		filter: 'stepForm',
		width: '100%', //设置容器宽度
		stepWidth: '750px',
		height: '650px',
		stepItems: [{
			title: '填写'
		}, {
			title: '完成'
		}]
	});
	form.on('submit(formStep)', function (data) {
		step.next('#stepForm');
		return false;
	});
	$('.pre').click(function () {
		step.pre('#stepForm');
	});
	$('.next').click(function () {
		step.next('#stepForm');
	});
})

//新增框提交内容实现
layui.use(['form', 'upload', 'layer'], function () {
	var form = layui.form;
	//方法提交
	$('#testSubmitBtn').on('click', function (data) {
		form.submit('storageRule', function (data) { // 注：v2.7.0 新增
			// 回调函数返回结果跟上述 submit 事件完全一致
			field = data.field;
			console.log(data.field)
			// do something
			//protoJson();
			buildStorageRuleJson();
		});
		return false;
	});

	//隐藏长度框
	form.on('select(dump_method_select)', function (data) {
		console.log(data.value);
		if (data.value == "expired") {
			document.getElementById("dump_method_cfg").value = ""
		} else if (data.value == "size") {
			document.getElementById("dump_method_cfg").value = 5
		}
		form.render();
	});


	form.on('select(expired_select)', function (data) {
		console.log(data.value);
		if (data.value == "FV") {
			$("#expired_value").hide()
			document.getElementById("expired_value").value = 0
		} else {
			$("#expired_value").show()
			document.getElementById("expired_value").value = ""
		}
		form.render();
	});

});

//增加/加入一个文件存储规则JSON
function buildStorageRuleJson() {
	var arrSRule = storage_rules_config_request.rules_cfg;
	var id = storage_rules_config_request.max_id;
	id++;
	var SRuleWeb = {
		"cfgType": "10",
		"cfgName": "storage_rules.json",
		"content": ""
	}
	var SRuleSave = {
		"cfg_type": 10,
		"max_id": "",
		"rules_cfg": ""
	}
	if (id) {
		SRules = {
			"id": 1,
			"name": "航迹c",
			"dump_method": { "method": "expired", "cfg": "3" }, //2023-11-08, 默认使用超期方法存储, 支持时长（单位分钟）和大小(单位GB)2种方式
			"dump_path": ["空间1", "航迹", "/data/123"], // /空间1/视频/data/123，默认为空；路径格式 空间 + 格式 + 存储路径
			"auto_backups": ["空间2", "航迹", "/data/123"],
			// 可选，路径有效，则需要自动备份，结合定时备份使用，备份后数据路径/空间2/视频/data/123
			"expired": { "val": 1, "unit": "day" }, // 数据过期时间，默认0，单位为天，标识数据是否可被使用，0 - 不超期, "unit" : "day" / "min" / "hour" 
			"level": 5, //数据重要等级，范围1~5，默认5,1等级最高，5等级最低
			"storage_capacity": { "val": 100, "unit": "GB" }, //此类文件最大空间容量，单位GB / TB
			"file_prefix": "dat" //默认dat
		}
		SRules.id = id;
	} else {
		arrSRule = []
		SRules = {
			"id": 1,
			"name": "航迹c",
			"dump_method": { "method": "expired", "cfg": "3" }, //2023-11-08, 默认使用超期方法存储, 支持时长（单位分钟）和大小(单位GB)2种方式
			"dump_path": ["空间1", "航迹", "/data/123"], // /空间1/视频/data/123，默认为空；路径格式 空间 + 格式 + 存储路径
			"auto_backups": ["空间2", "航迹", "/data/123"],
			// 可选，路径有效，则需要自动备份，结合定时备份使用，备份后数据路径/空间2/视频/data/123
			"expired": { "val": 1, "unit": "day" }, // 数据过期时间，默认0，单位为天，标识数据是否可被使用，0 - 不超期, "unit" : "day" / "min" / "hour" 
			"level": 5, //数据重要等级，范围1~5，默认5,1等级最高，5等级最低
			"storage_capacity": { "val": 100, "unit": "GB" }, //此类文件最大空间容量，单位GB / TB
			"file_prefix": "dat" //默认dat
		}
		id = 0;
		SRules.id = 0;
	}
	console.log(field);
	SRules.name = field.name
	var dump_method_save = {
		"method": "",
		"cfg": ""
	}
	dump_method_save.method = field.dump_method_select
	dump_method_save.cfg = parseInt(field.dump_method_cfg)
	SRules.dump_method = dump_method_save
	var dump_path_save = []
	dump_path_save.push(field.dump_path_select1)
	dump_path_save.push(field.dump_path_select2)
	dump_path_save.push(field.dump_path)
	SRules.dump_path = dump_path_save
	var auto_backups_save = []
	auto_backups_save.push(field.auto_backups_select1)
	auto_backups_save.push(field.auto_backups_select2)
	auto_backups_save.push(field.auto_backups)
	SRules.auto_backups = auto_backups_save
	var expired_save = {
		"val": "",
		"unit": ""
	}
	// if (field.expired_select == "year") {
	// 	expired_save.val = parseInt(field.expired_value) * 365
	// 	expired_save.unit = "year"
	// } else if (field.expired_select == "month") {
	// 	expired_save.val = parseInt(field.expired_value) * 30
	// 	expired_save.unit = "month"
	// } else if (field.expired_select == "day") {
	// 	expired_save.val = parseInt(field.expired_value)
	// 	expired_save.unit = "day"
	// } else if (field.expired_select == "hour") {
	// 	expired_save.val = parseInt(field.expired_value)
	// 	expired_save.unit = "hour"
	// } else if (field.expired_select == "min") {
	// 	expired_save.val = parseInt(field.expired_value)
	// 	expired_save.unit = "min"
	// }
	expired_save.val = parseInt(field.expired_value)
	expired_save.unit = field.expired_select
	// expired_save.val = parseInt(field.expired_value)
	// expired_save.unit = field.expired_select
	SRules.expired = expired_save
	SRules.level = parseInt(field.level)
	var storage_capacity_save = {
		"val": "",
		"unit": ""
	}
	storage_capacity_save.val = parseInt(field.maxsize_val)
	storage_capacity_save.unit = field.maxsize_unit
	SRules.storage_capacity = storage_capacity_save
	SRules.file_prefix = field.file_prefix
	arrSRule.push(SRules);
	SRuleSave.rules_cfg = arrSRule;
	SRuleSave.max_id = id;
	SRuleWeb.content = JSON.stringify(SRuleSave);
	console.log(SRuleSave);
	postQuestSave(SRuleWeb);
	alert("新增成功！");
	window.location.reload();

}

//表格初始化
function bootstrapTable_init() {
	$("#table_page").bootstrapTable('destroy').bootstrapTable({
		data: tablelist,
		dataType: 'json',
		pagination: true,                   //是否显示分页（*）
		cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
		sortOrder: "asc",                   //排序方式
		sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
		pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
		pageSize: 10,                     //每页的记录行数（*）
		pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
		strictSearch: true,
		minimumCountColumns: 1,             //最少允许的列数
		uniqueId: "id",                     //每一行的唯一标识，一般为主键列
		onEditableSave: onEditableSave,
		columns: [
			[{
				title: '基础信息',
				align: 'center',
				colspan: 2
			}, {
				title: '文件切片方法',
				align: 'center',
				colspan: 2
			}, {
				title: '存储信息',
				align: 'center',
				colspan: 3
			}, {
				title: '自动备份信息',
				align: 'center',
				colspan: 3
			}, {
				title: '有效时长',
				align: 'center',
				colspan: 2
			}, {
				title: '最大空间容量',
				align: 'center',
				colspan: 2
			}, {
				title: '其他信息',
				align: 'center',
				colspan: 3
			}]
			,
			[{
				field: 'ID',
				align: 'center',
				title: '序号',
				width: 60,
				formatter: function (value, row, index) {
					return index + 1;
				}
			}, {
				field: 'name',
				align: 'center',
				title: '规则名称',
				width: 80,
				editable: editable_cn
			}, {
				field: 'dump_method_method',
				align: 'center',
				title: '方式',
				width: 80,
				editable: {
					type: 'select',
					title: '值类型',
					source: [{
						value: "时长(分钟)",
						text: "时长(分钟)"
					}, {
						value: "大小(GB)",
						text: "大小(GB)"
					}]
				}
			}, {
				field: 'dump_method_cfg',
				align: 'center',
				title: '值',
				width: 80,
				editable: {
					type: 'number',
					min: 0,
					emptytext: '未定义'
				}
			}, {
				field: 'dump_path1',
				align: 'center',
				title: '空间',
				width: 80,
				editable: {
					type: 'select',
					title: '值类型',
					source: [{
						value: "空间1",
						text: "空间1"
					}, {
						value: "空间2",
						text: "空间2"
					}]
				}
			}, {
				field: 'dump_path2',
				align: 'center',
				title: '类型',
				width: 80,
				editable: {
					type: 'select',
					emptytext: '未定义',
					title: '值类型',
					source: filetype_select_option_arr
				}
			}, {
				field: 'dump_path3',
				align: 'center',
				title: '路径',
				width: 80,
				class: 'colStyle',
				// cellStyle:formatTableUnit,
				// formatter: paramsMatter,
				editable: {
					type: 'text',
					title: '输入新的内容',
					emptytext: '未定义'
				}
			}, {
				field: 'auto_backups1',
				align: 'center',
				title: '空间',
				width: 80,
				editable: {
					type: 'select',
					title: '值类型',
					source: [{
						value: "空间1",
						text: "空间1"
					}, {
						value: "空间2",
						text: "空间2"
					}]
				}
			}, {
				field: 'auto_backups2',
				align: 'center',
				title: '类型',
				width: 80,
				editable: {
					type: 'select',
					emptytext: '未定义',
					title: '值类型',
					source: filetype_select_option_arr
				}
			}, {
				field: 'auto_backups3',
				align: 'center',
				title: '路径',
				width: 80,
				class: 'colStyle',
				// formatter: paramsMatter,
				editable: {
					type: 'text',
					title: '输入新的内容',
					emptytext: '未定义'
				}
			}, {
				field: 'expired_val',
				align: 'center',
				title: '值',
				width: 80,
				editable: timeLimit
			}, {
				field: 'expired_unit',
				align: 'center',
				title: '单位',
				width: 80,
				editable: {
					type: 'select',
					title: '值类型',
					source: [{
						value: "year",
						text: "年"
					}, {
						value: "month",
						text: "月"
					}, {
						value: "day",
						text: "天"
					}, {
						value: "hour",
						text: "小时"
					}, {
						value: "min",
						text: "分钟"
					}, {
						value: "FV",
						text: "永久"
					}]
				}
			}, {
				field: 'storage_capacity_val',
				align: 'center',
				title: '值',
				width: 80,
				editable: {
					type: 'number',
					min: 0,
					emptytext: '未定义'
				}
			}, {
				field: 'storage_capacity_unit',
				align: 'center',
				title: '单位',
				width: 80,
				editable: {
					type: 'select',
					title: '值类型',
					source: [{
						value: "TB",
						text: "TB"
					}, {
						value: "GB",
						text: "GB"
					}]
				}
			}, {
				field: 'level',
				align: 'center',
				title: '等级',
				width: 80,
				editable: {
					type: 'select',
					title: '值类型',
					source: [{
						value: "1",
						text: "1"
					}, {
						value: "2",
						text: "2"
					}, {
						value: "3",
						text: "3"
					}, {
						value: "4",
						text: "4"
					}, {
						value: "5",
						text: "5"
					}]
				}
			}, {
				field: 'file_prefix',
				align: 'center',
				title: '文件前缀',
				width: 80,
				editable: editable_cn
			}, {
				field: 'id',
				align: 'center',
				title: '删除',
				width: 80,
				formatter: function (value, row, index) {
					var id = value;
					var result = "";
					result += "<a href='javascript:;' class='btn btn-xs red' onclick=\"storage_rules_config_delete(" + id + ")\" title='删除'><span class='feather-trash-2'></span></a>";
					return result;
				}
			}
			]
		]
	});

}

//时间输入限制
function timeLimit(rowIndex) {
	// console.log(rowIndex)
	var data = $("#table_page").bootstrapTable('getData');
	// console.log(data[rowIndex].expired_unit)

	if (data[rowIndex].expired_unit == "year") {
		return {
			type: 'number',
			min: 1,
			max: 100
		}
	} else if (data[rowIndex].expired_unit == "month") {
		return {
			type: 'number',
			min: 1,
			max: 11
		}
	} else if (data[rowIndex].expired_unit == "day") {
		return {
			type: 'number',
			min: 1,
			max: 29
		}
	} else if (data[rowIndex].expired_unit == "hour") {
		return {
			type: 'number',
			min: 1,
			max: 23
		}
	} else if (data[rowIndex].expired_unit == "min") {
		return {
			type: 'number',
			min: 1,
			max: 59
		}
	} else if (data[rowIndex].expired_unit == "FV") {
		return {
			disabled: true
		}
	}


}


//编辑保存
function onEditableSave(field, row, rowIndex, oldValue, $el) {
	var data = $("#table_page").bootstrapTable('getData');
	var objChange = data[rowIndex];
	var idChange = objChange.id;
	var arr = storage_rules_config_request.rules_cfg;
	var SRuleWeb = {
		"cfgType": "10",
		"cfgName": "storage_rules.json",
		"content": ""
	}
	var SRuleSave = {
		"cfg_type": 10,
		"max_id": "",
		"rules_cfg": ""
	}
	if (field == "name") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].name = row[field];
			}
		}
	} else if (field == "dump_method_method") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				if (row[field] == "时长(分钟)") {
					arr[i].dump_method.method = "expired";
				} else if (row[field] == "大小(GB)") {
					arr[i].dump_method.method = "size";
					arr[i].dump_method.cfg = 5
				}
			}
		}
	} else if (field == "dump_method_cfg") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].dump_method.cfg = parseInt(row[field]);
			}
		}
	} else if (field == "dump_path1") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].dump_path[0] = row[field];
			}
		}
	} else if (field == "dump_path2") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].dump_path[1] = row[field];
			}
		}
	} else if (field == "dump_path3") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].dump_path[2] = row[field];
			}
		}
	} else if (field == "auto_backups1") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].auto_backups[0] = row[field];
			}
		}
	} else if (field == "auto_backups2") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].auto_backups[1] = row[field];
			}
		}
	} else if (field == "auto_backups3") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].auto_backups[2] = row[field];
			}
		}
	} else if (field == "expired_val") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				console.log(arr[i].expired.unit)
				console.log(arr[i].expired.val)
				// if (arr[i].expired.unit == "year") {
				// 	if (0 < parseInt(row[field]) && 101 > parseInt(row[field])) {
				// 		arr[i].expired.val = parseInt(row[field]);
				// 	} else {
				// 		layer.msg('修改失败,范围是1-100年,请重新修改', { icon: 2 });
				// 		return
				// 	}
				// }
				arr[i].expired.val = parseInt(row[field]);
			}
		}
	} else if (field == "expired_unit") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				// if (row[field] == "year") {
				// 	arr[i].expired.val = arr[i].expired.val
				// } else 
				if (row[field] == "month") {
					if (arr[i].expired.val > 11) {
						arr[i].expired.val = 1
					}
				} else if (row[field] == "day") {
					if (arr[i].expired.val > 29) {
						arr[i].expired.val = 1
					}
				} else if (row[field] == "hour") {
					if (arr[i].expired.val > 23) {
						arr[i].expired.val = 1
					}
				} else if (row[field] == "min") {
					if (arr[i].expired.val > 59) {
						arr[i].expired.val = 1
					}
				} else if (row[field] == "FV") {
						arr[i].expired.val = 0
				}

				arr[i].expired.unit = row[field]

			}
		}
	} else if (field == "storage_capacity_val") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].storage_capacity.val = parseInt(row[field]);
			}
		}
	} else if (field == "storage_capacity_unit") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].storage_capacity.unit = row[field];
			}
		}
	} else if (field == "level") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].level = row[field];
			}
		}
	} else if (field == "file_prefix") {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].id == idChange) {
				arr[i].file_prefix = row[field];
			}
		}
	}
	SRuleSave.rules_cfg = arr;
	SRuleSave.max_id = storage_rules_config_request.max_id;
	SRuleWeb.content = JSON.stringify(SRuleSave)

	////////////////////////////////////////////////
	////////////////请求发送并重新建表///////////////
	////////////////////////////////////////////////
	var xhr = new XMLHttpRequest();
	// 配置请求
	xhr.open('POST', 'http://' + ipm + ':8081/dict/save', true);
	xhr.setRequestHeader('content-Type', 'application/json');
	// 发送 JSON 数据
	xhr.send(JSON.stringify(SRuleWeb));
	// 监听请求的状态
	xhr.onreadystatechange = function () {
		console.log(xhr.readyState);
		if (xhr.readyState === 4 && xhr.status === 200) {
			console.log(xhr.responseText);
			$.ajax({
				url: 'http://' + ipm + ':8081/dict/query',
				type: 'POST',
				contentType: 'application/json',
				dataType: 'json',
				data: {},
				success: function (response) {
					tablelist = []
					storageRulesConfigRead(response)
					bootstrapTable_init();
				}
			});
		}
	};
	layer.msg('修改成功', { icon: 1 });
}

//文件存储规则，删除函数
function storage_rules_config_delete(args) {
	var arrSRule = storage_rules_config_request.rules_cfg;
	console.log(arrSRule);
	console.log(args);
	for (var i = 0; i < arrSRule.length; i++) {
		if (arrSRule[i].id == args) {
			arrSRule.splice(i, 1);
		}
	}
	var SRuleWeb = {
		"cfgType": "10",
		"cfgName": "storage_rules.json",
		"content": "",
	}
	storage_rules_config_request.rules_cfg = arrSRule;
	SRuleWeb.content = JSON.stringify(storage_rules_config_request)
	console.log(SRuleWeb)
	console.log(arrSRule)
	postQuestSave(SRuleWeb);
	window.location.reload();
}

